import Ipha_tool from "../Ipha_tool";
import Ipha_ComponentBasic from "./Ipha_ComponentBasic";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;

/**
 * 自动使大小包含所有子节点,该组件会改变锚点
 */
@ccclass
@executeInEditMode
@menu("ipha组件/自动大小")
export default class Ipha_AutoSize extends Ipha_ComponentBasic {

    comName: string = "自动使大小包含所有子节点,该组件会改变锚点";

    @property({ displayName: "左偏差" })
    private leftOffset: number = 0;
    @property({ displayName: "右偏差" })
    private rightOffset: number = 0;
    @property({ displayName: "上偏差" })
    private topOffset: number = 0;
    @property({ displayName: "下偏差" })
    private bottomOffset: number = 0;

    private _isAutoSize: boolean = true;
    get isAutoSize() { return this._isAutoSize; }
    set isAutoSize(bool: boolean) { this._isAutoSize = bool; }

    protected start(): void {
        if (this._isAutoSize) {
            this.autoSize();
        }
    }


    autoSize() {
        if (this.node.childrenCount > 0) {
            let left: number[] = [];
            let right: number[] = [];
            let top: number[] = [];
            let bottom: number[] = [];

            this.node.children.forEach(elem => {
                this.childrenRead(elem, left, right, top, bottom);
            });

            this.node.width = Math.round((Math.max(...right) - Math.min(...left)) * 100) / 100 + this.leftOffset + this.rightOffset;
            this.node.height = Math.round((Math.max(...top) - Math.min(...bottom)) * 100) / 100 + this.topOffset + this.bottomOffset;
            let wPos = Ipha_tool.pos.getNodeWordPos(this.node);
            this.node.anchorX = (wPos.x - Math.min(...left) + this.leftOffset) / this.node.width;
            this.node.anchorY = (wPos.y - Math.min(...bottom) + this.bottomOffset) / this.node.height;
        }
    }

    childrenRead(node: cc.Node, left?: number[], right?: number[], top?: number[], bottom?: number[]) {
        if (!node.active || !node || !node.isValid) {
            return;
        }
        let pos = Ipha_tool.pos.getNodeWordPos(node);
        left.push(pos.x - (node.width * node.scaleX * node.anchorX));
        right.push(pos.x + (node.width * node.scaleX * (1 - node.anchorX)));
        top.push(pos.y + (node.height * node.scaleY * (1 - node.anchorY)));
        bottom.push(pos.y - (node.height * node.scaleY * node.anchorY));

        if (node.childrenCount > 0) {
            node.children.forEach(elem => {
                this.childrenRead(elem, left, right, top, bottom);
            });
        }
    }

    protected update(dt: number): void {
        if (this._isAutoSize) {
            this.autoSize();
        }
    }

}
